package logic

import (
	"context"
	"encoding/json"
	"time"
	"zhihu/models/cache"
	"zhihu/models/mysql"

	"zhihu/zhihurpc/internal/svc"
	"zhihu/zhihurpc/zhihurpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProblemHotLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProblemHotLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProblemHotLogic {
	return &ProblemHotLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// top10问题列表
func (l *ProblemHotLogic) ProblemHot(in *zhihurpc.ProblemHotRequest) (*zhihurpc.ProblemHotResponse, error) {
	// todo: add your logic here and delete this line
	var problems []mysql.Problem
	cacheData := cache.Rdb.Get(l.ctx, "problem_list").Val()
	if cacheData == "" {
		mysql.DB.Debug().Order("hot desc").Limit(10).Find(&problems)
		jsonData, _ := json.Marshal(problems)
		cache.Rdb.Set(l.ctx, "problem_list", jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &cacheData)
	}
	var problemList []*zhihurpc.HotList
	for _, problem := range problems {
		list := zhihurpc.HotList{
			Id:     int64(problem.ID),
			UserId: problem.UserId,
			Title:  problem.Title,
			Image:  problem.Image,
			Info:   problem.Info,
			Like:   problem.Like,
			Hot:    problem.Hot,
		}
		problemList = append(problemList, &list)
	}
	return &zhihurpc.ProblemHotResponse{
		List: problemList,
	}, nil
}
